package com.uflower.user.controller;

import cn.hutool.captcha.LineCaptcha;
import com.uflower.common.utils.R;
import com.uflower.user.entity.UserEntity;
import com.uflower.user.service.UserService;
import com.uflower.user.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.script.ScriptException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录和注册")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 验证码
     */
    @ApiOperation(value = "登录验证码接口", notes = "获取登录验证码")
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        LineCaptcha captcha = userService.getCaptcha();
        session.setAttribute("code",captcha.getCode());
        try{
        // 输出到页面
        captcha.write(response.getOutputStream());
        // 打印日志
            System.out.println("生成的验证码:"+captcha.getCode());
        // 关闭流
        response.getOutputStream().close();
        } catch(
        IOException e)

        {
            e.printStackTrace();
        }

}
    /**
     * 登录
     */
    @ApiOperation("用户登录")
    @ResponseBody
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ScriptException {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String verifyCode = loginVo.getVerifyCode();
        String sessionCheckCode = (String) request.getSession().getAttribute("code");
        if (!sessionCheckCode.equals(verifyCode)){
            return R.error("验证码错误");
        }
        //用户信息
        UserEntity user = userService.queryByUserName(username);

        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(password)) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0 || user.getStatus() == null){
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token
        String token = userService.createToken(user.getId(),username);
        //HttpServerletRequest 装请求信息类
        //HttpServerletRespionse 装相应信息的类
        Cookie cookie=new Cookie("token",token);
        cookie.setPath("/api");
        response.addCookie(cookie);
//        request.setAttribute("cookie",cookie); //将需要送到jsp的数据放到request请求域中,让request帮忙带到jsp
//        request.getRequestDispatcher("/index").forward(request,response);
//        response.sendRedirect("index");

        return R.ok();
    }


    /**
     * 退出
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public R logout(HttpServletRequest request,HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {

            cookie.setMaxAge(0);

            cookie.setPath("/");

            response.addCookie(cookie);
        }
        return R.ok();
    }
}
